#include "chat.h"
#include "ui_chat.h"
#include "main.h"

//#include "mainwindow.h"
//#include "lockerwidget.h"
//#include "small_friend.h"
//#include "get_user.h"



ChatWidget::ChatWidget(Friend sender, Friend receiver, QString senderHeadPath, QString receiverHeadPath, QWidget *parent)
    : QWidget(parent), sender(sender), receiver(receiver), ui(new Ui::Widget)
{
    ui->setupUi(this);
    //

    m_socket = new SerSocket();

    connect(this,&ChatWidget::Text,m_socket,&SerSocket::ClientSendingText);
    connect(m_socket,&SerSocket::GetMsgId,this,&ChatWidget::update_msgid);

    QGridLayout* glayout = new QGridLayout();
    // 设置双方信息
    ui->senderInfo->setText("昵称："+sender.name+"\n职责："+sender.job+"\nip："+sender.ip);
    ui->receiverInfo->setText("昵称："+receiver.name+"\n职责："+receiver.job+"\nip："+receiver.ip);
    ui->senderHead->setPixmap(QPixmap(senderHeadPath));
    ui->receiverHead->setPixmap(QPixmap(receiverHeadPath));

    // 聊天框滚动效果
    scrollarea = new QScrollArea(ui->liaotiankuang);
    scrollarea->setWidgetResizable(true);
    scrollarea->setMinimumSize(339, 218);
    scrollarea->setStyleSheet("background-color: transparent;");
    scrollareacontent = new QWidget(ui->liaotiankuang);
    scrollarea->setWidget(scrollareacontent);
    // 设置聊天框垂直
    QVBoxLayout* scrollLayout = new QVBoxLayout();
    scrollLayout->addWidget(scrollarea);
    ui->liaotiankuang->setLayout(scrollLayout);

    glayout->addWidget(scrollareacontent);
    //    scrollareacontent->setLayout(glayout);
    //    // 聊天框自适应大小
    QSizePolicy sizePlc(QSizePolicy::Expanding, QSizePolicy::Expanding);
    scrollareacontent->setSizePolicy(sizePlc);

    // 聊天框内垂直布局
    playout = new QVBoxLayout(scrollareacontent);
    scrollareacontent->setLayout(playout);
    ui->liaotiankuang->setStyleSheet("background-color: white;");



    // 发给我的时候就有的，不知道干什么的
    //    mainwindow *window = new mainwindow();
    //    window->show();
    //    LockerWidget* a = new LockerWidget();
    //    a->show();
    //    user_information user1("001");
    //    small_friend* c = new small_friend(user1);
    //    c->show();
}

ChatWidget::~ChatWidget()
{
    delete ui;
}

void ChatWidget::resizeEvent(QResizeEvent *event){
    QSize newSize = ui->liaotiankuang->size();
    scrollarea->resize(newSize.width(), newSize.height());
}

void ChatWidget::on_send_clicked()
{

    // 先把文本框的消息取出来
    QString msg = ui->textEdit->toPlainText();
    qDebug() << msg;
    if(msg.isEmpty())
        return ;
    // 再清空文本框
    ui->textEdit->clear();

    qDebug() << ui->liaotiankuang->width() << " " << ui->liaotiankuang->height();
    qDebug() << scrollareacontent->width() << " " << scrollareacontent->height();


    QString friend_name = receiver.name; //####
    //    QJsonObject now_friend = name_list->value(friend_name).toObject();
    //    now_uid = now_friend.value("uid").toString();
    QJsonObject text_bag;
    text_bag.insert("UID", QString::number(sender.id));
    text_bag.insert("RID",QString::number(receiver.id));
    text_bag.insert("content",msg);
    QJsonDocument jsonDocument;
    jsonDocument.setObject(text_bag);
    QByteArray tbox = jsonDocument.toJson();
    emit Text(tbox,0x06);

    Message m_msg;
    m_msg.msg = msg;
    m_msg.rid = receiver.id;
    m_msg.tid = sender.id;
    m_msg.time = QDateTime::currentDateTime();
    msg_que.enqueue(m_msg);
    //now_msg =ui->textEdit->toPlainText();
    //ui->history->appendPlainText(use_name+" [out] "+now_msg+"\n");

    ChatBubbleAndHead* b1=new ChatBubbleAndHead(m_msg, SENDER);
    //ChatBubbleAndHead* b2=new ChatBubbleAndHead(pkgmsg, 0);
    playout->addWidget(b1,0,Qt::AlignRight | Qt::AlignBottom);
    // playout->addWidget(b2,0,Qt::AlignLeft | Qt::AlignTop);


    //    ui->textBrowser->append(msg);
    //    ui->textBrowser->setStyleSheet("border: 1px solid gray; background-color: #f5f1f0;");
    //    ui->textBrowser->append(bubble1);
    // 再发送消息
}

void ChatWidget::on_file_button_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this, "请选择文件");
    if (!filePath.isEmpty()){
        // 上传服务器

        //

        // 发送文件的显示
        sendFile(QFileInfo(filePath).fileName());

    }
}

void ChatWidget::sendMessage(Message msg){
    ChatBubble* b1=new ChatBubble(msg, 1);
    playout->addWidget(b1,0,Qt::AlignRight | Qt::AlignBottom);
}
void ChatWidget::receiveMessage(Message msg){
    ChatBubble* b1=new ChatBubble(msg, 0);
    playout->addWidget(b1,0,Qt::AlignLeft | Qt::AlignTop);
}

void ChatWidget::sendFile(QString fileName){
    // 显示正在传输的文件
    int jindu = 0;
    ui->senderFileName->setText("正在发送："+fileName);
    ui->senderProgressBar->setValue(jindu);
    // 传输文件

    // 进度条
    ui->senderProgressBar->setValue(jindu);
    // 完成后
    ui->senderFileName->setText("已完成发送："+fileName);

}
void ChatWidget::receiveFile(QString fileName){
    // 显示正在传输的文件
    int jindu = 0;
    ui->senderFileName->setText("正在接收："+fileName);
    ui->senderProgressBar->setValue(jindu);
    // 传输文件

    // 进度条
    ui->senderProgressBar->setValue(jindu);
    // 完成后
    ui->senderFileName->setText("已完成接收："+fileName);
}


void ChatWidget::update_msgid(const int& mid){
    Message m_msg = msg_que.dequeue();
    m_msg.id = mid;
    db.AddMessage(m_msg);
}

void ChatWidget::getUpdateMessage(const QJsonArray &msg_list)
{
    int num = msg_list.size();
    for (int i =0; i < num; i++)
    {
        QJsonObject Friend = msg_list.at(i).toObject();
        Message Msg;
        Msg.tid = Friend.value("TID").toString().toInt();
        Msg.rid = Friend.value("RID").toString().toInt();
        Msg.msg = Friend.value("content").toString();
        Msg.id = Friend.value("MID").toString().toInt();
        Msg.time = QDateTime::fromString(Friend.value("time").toString(), "yyyy-MM-dd hh:mm:ss");
        db.AddMessage(Msg);
        //ui->history->appendPlainText(id_list->value(QString(Msg.tid)).toString()+"[in]"+Msg.msg);
        user recv = getUser(QString::number(receiver.id));
        if(recv.chat->isVisible()){
            recv.chat->receiveMessage(Msg);
        }
    }

}
